<template>
	<div>
		<el-form
			class="pointAndRebate"
			ref="AgentRebatesForm"
			:label-width="labelWidth"
			:model="values"
		>
			<div v-for="config in pointConfigs" :key="config.id">
				<el-form-item
					v-if="checkShow(config.name)"
					:label="`${config.label}:`"
					:required="checkEdit(config.name)"
				>
					<PointTable
						:class="config.name"
						:name="config.name"
						v-model="config.value"
						:maxValueRange="config.maxValueRange"
						:subLabel="config.subLabel"
						:columns="config.columns"
						:isEdit="checkEdit(config.name)"
					/>
					<slot :name="config.name" />
				</el-form-item>
			</div>
		</el-form>
		<AgentPointSetAllSub
			:loading="agentPointSetAllSubLoading"
			:visible="agentPointSetAllSubVisible"
			:agentData="agentData"
			:getPoints="getValues"
			:commissionModel="commissionModel"
			@ok="(data) => agentPointSetAllSubOk(data)"
			@close="agentPointSetAllSubVisible = false"
		/>
	</div>
</template>

<script>
import PointTable from './PointTable.vue'
import AgentPointSetAllSub from '@/components/AgentPointSetAllSub'

import { pointConfigs, initRow } from './config'

export default {
	name: 'AgentRebates',
	components: {
		PointTable,
		AgentPointSetAllSub
	},
	props: {
		isEdit: {
			type: Boolean || Array,
			default: false
		},
		isShow: {
			type: Boolean || Array,
			default: true
		},
		// 是否“编辑”会员返点
		isEditMemberPlatform: {
			type: Boolean,
			default: false
		},
		labelWidth: {
			type: String,
			default: '230px'
		},
		// 查询返点参数
		queryRebateRateParams: {
			type: Object,
			default: undefined
		},
		// 查询佣金参数
		queryCommissionRateParams: {
			type: Object,
			default: undefined
		},
		agentData: {
			type: Object,
			default: undefined
		},
		isMember: {
			type: Boolean,
			default: false
		},
		memberPlatform: {
			type: Object,
			default: () => ({})
		},
		// 1 占成，2 返佣
		commissionModel: {
			type: Number,
			default: 1
		},

		isOpenProxyAudit: {
			type: Boolean,
			default: undefined
		},
		openCommissionRateList: {
			type: Array,
			default: undefined
		},
		openMemberPlatform: {
			type: Object,
			default: () => ({})
		},
		openProxyRebateRateList: {
			type: Array,
			default: undefined
		}
	},
	data() {
		return {
			pointConfigs: [],
			rebateAllotMode: 1,

			// 修改返点信息弹框
			agentPointSetAllSubLoading: false,
			agentPointSetAllSubVisible: false
		}
	},
	computed: {
		values() {
			const _values = {}
			this.pointConfigs.forEach((conf) => {
				_values[conf.name] = conf.value
			})
			return _values
		}
	},
	watch: {
		isEdit: {
			handler(bool) {
				this.$nextTick(() => {
					this.queryLimits()
				})
			},
			immediate: true
		},
		// 处理页面缓存问题
		$route: {
			handler(route) {
				this.resetFields()
				this.$nextTick(() => {
					if (['upTopProxyAudit', 'addAgent'].includes(route.name)) {
						return
					}
					if (this.isOpenProxyAudit) {
						this.openProxyBackfill()
					} else {
						this.queryRebateRate()
						if (this.commissionModel === 2) {
							this.queyrCommissionRate()
						}
					}
				})
			},
			deep: true,
			immediate: true
		},
		commissionModel: {
			handler(newVal) {
				this.pointConfigs = pointConfigs({ commissionModel: newVal })
				this.resetFields()
				this.$nextTick(() => {
					this.queryLimits()
				})
			},
			immediate: true
		}
	},
	created() {
		// this.pointConfigs = pointConfigs({ commissionModel: this.commissionModel })
	},
	mounted() {
		this.validate = this.$refs['AgentRebatesForm'].validate
	},
	methods: {
		checkEdit(name) {
			if (name === 'agentPoint') {
				return false
			}
			if (typeof this.isEdit === 'boolean') {
				return this.isEdit
			}

			if (Array.isArray(this.isEdit)) {
				return this.isEdit.includes(name)
			}
			return false
		},
		checkShow(name) {
			// 单独处理代理返水
			if (name === 'agentPoint') {
				return Array.isArray(this.isShow) && this.isShow.includes(name)
			}
			if (typeof this.isShow === 'boolean') {
				return this.isShow
			}
			if (Array.isArray(this.isShow)) {
				return this.isShow.includes(name)
			}
			return false
		},
		clearValidate(prop) {
			this.$refs['AgentRebatesForm'].clearValidate(prop)
		},
		async resetFields() {
			this.$refs['AgentRebatesForm'].resetFields()
			this.pointConfigs.forEach((conf) => {
				conf.value = initRow(conf.columns)
			})
		},
		getValues(confNames) {
			const fdConfNames = [
				'teamRebates',
				'teamContribution',
				'memberPlatform'
			]
			const fyConfNames = ['commissionDzRebates', 'memberPlatform']
			const _confNames =
				confNames ||
				(this.commissionModel === 1 ? fdConfNames : fyConfNames)
			console.log(confNames)

			const configs = _confNames
				? this.pointConfigs.filter((conf) => {
						const name = conf.name
						return _confNames.includes(name)
				  })
				: this.pointConfigs

			return configs.map((config) => {
				if (this.commissionModel === 1) {
					if (config.name === 'teamRebates') {
						// 分成字段
						const dzValues = this.pointConfigs.find((conf) => {
							return conf.name === 'dzRebates'
						}).value

						return {
							...config.query,
							...config.value,
							...{
								texasRebate: dzValues.texasRebate,
								texasInsuranceRebate:
									dzValues.texasInsuranceRebate,
								valueAddedServiceRebate:
									dzValues.valueAddedServiceRebate
							}
						}
					}
				}

				if (this.commissionModel === 2) {
					if (config.name === 'commissionDzRebates') {
						// 合并 otherCommission
						const otherCommissionVals = this.pointConfigs.find(
							(conf) => {
								return conf.name === 'otherCommission'
							}
						).value

						return {
							serialNo: 1,
							...config.query,
							...config.value,
							...otherCommissionVals
						}
					}
				}
				return {
					serialNo: 1,
					...config.query,
					...config.value
				}
			})
		},

		// 兼容开启入口权限待审核状态
		openProxyBackfill() {
			this.pointConfigs.forEach((conf) => {
				if (conf.name === 'memberPlatform') {
					conf.value = Object.assign(
						{},
						conf.value,
						this.openMemberPlatform
					)
				}

				if (
					conf.name === 'commissionDzRebates' ||
					conf.name === 'otherCommission'
				) {
					conf.value = Object.assign(
						{},
						conf.value,
						this.openCommissionRateList[0]
					)
				}

				if (['dzRebates', 'teamRebates'].includes(conf.name)) {
					conf.value = Object.assign(
						{},
						conf.value,
						this.openProxyRebateRateList.find(
							(data) => data.zhanchengFlag === 0
						)
					)
				}
				if (['teamContribution'].includes(conf.name)) {
					conf.value = Object.assign(
						{},
						conf.value,
						this.openProxyRebateRateList.find(
							(data) => data.zhanchengFlag === 1
						)
					)
				}
			})
		},
		queryLimits() {
			if (typeof this.isEdit === 'boolean' && this.isEdit) {
				this.pointConfigs.forEach((conf) => {
					this.queryLimit(conf)
				})
				return
			}
			if (Array.isArray(this.isEdit)) {
				this.pointConfigs.forEach((conf) => {
					if (this.isEdit.includes(conf.name)) {
						this.queryLimit(conf)
					}
				})
				return
			}
		},
		async queryLimit(config, resCallback) {
			let apiName = 'rebateRateQueryLimit'

			if (
				this.commissionModel === 2 &&
				['commissionDzRebates', 'otherCommission'].includes(config.name)
			) {
				apiName = 'commissionRateQueryLimit'
			}
			const res = await this.$api[apiName]({
				...config.query,
				commissionModel: this.commissionModel
			})

			if (res.code === 200 && res.data) {
				let data = res.data

				// 占成取 {key}Zhancheng 限制
				if (config.query.zhanchengFlag === 1) {
					const _data = {}
					for (const key in data) {
						if (key.includes('Zhancheng')) {
							_data[key.replace('Zhancheng', 'Rebate')] =
								data[key]
						}
					}

					data = _data
				}
				if (resCallback) {
					config['maxValueRange'] = resCallback(data)
				} else {
					config['maxValueRange'] = data
				}
			}
		},

		// 回填表单
		backfill(config, values) {
			let isBackfill = true

			if (this.isMember) {
				config.query.userType = 0
			}

			Object.keys(config.query).forEach((k) => {
				if (
					Object.keys(config.query).length > 0 &&
					config.query[k] !== values[k]
				) {
					isBackfill = false
				}
			})

			if (isBackfill && config.value.isBackfill && values.status === 1) {
				config.value.isBackfill = false
			}
			if (isBackfill && !config.value.isBackfill) {
				config.value = { ...values, isBackfill }
			}
		},
		// 获取返佣数据
		async queyrCommissionRate(params) {
			if (!this.queryCommissionRateParams && !params) return
			const _params = Object.assign(
				{},
				this.queryCommissionRateParams,
				params
			)

			try {
				const res = await this.$api.commissionRateQuery(_params)
				if (res.code === 200 && res.data) {
					const rebate = res.data.find((item) => {
						if (_params.status !== undefined) {
							return item.status === _params.status
						} else {
							return item.status === 1
						}
					})
					this.pointConfigs.forEach((conf) => {
						if (conf.name === 'commissionDzRebates') {
							conf.value = {
								...rebate,
								isBackfill: true
							}
						}
						if (conf.name === 'otherCommission') {
							conf.value = {
								otherCommission: rebate.otherCommission,
								isBackfill: true
							}
						}
					})
				}
			} catch (err) {
				throw err
			}
		},

		getApi() {
			// [21:50] Bicycle - 后端
			// qeuryProxy是查返点和占成模式的
			// [21:51] Bicycle - 后端
			// 佣金模式调用commissionRebate/query接口

			if (this.isMember) {
				return this.$api.getRebateRateQueryMember
			} else {
				if (this.commissionModel === 2) {
					return this.$api.getRebateRateQuery
				}
				return this.$api.getRebateRateQueryProxy
			}
		},
		// 获取返点信息
		async queryRebateRate(params) {
			if (!this.queryRebateRateParams && !params) return

			const _params = Object.assign(
				{},
				this.queryRebateRateParams,
				params
			)

			const res = await this.getApi()(_params)

			if (res.code === 200 && res.data.length > 0) {
				res.data.forEach((rebate) => {
					const status = [1, 3]
					if (_params.status !== undefined) {
						status.push(_params.status)
					}

					if (status.includes(rebate.status)) {
						this.pointConfigs
							.filter((rebate) => {
								if (this.commissionModel === 2) {
									return [
										'memberPlatform',
										'agentPoint'
									].includes(rebate.name)
								}
								return true
							})
							.forEach((conf) => {
								conf.value.isBackfill = false

								this.backfill(conf, rebate)
							})
					}
				})
			}
			// else if(res.data.length === 0 && _params.status === 1){
			// 	this.openProxyBackfill()
			// }

			// 处理团队返点中的德州保险（团队占成）
			// this.$nextTick(() => {
			// 	const zcTexasInsuranceRebate = this.teamContributionConfig.value.texasInsuranceRebate
			// 	this.teamRebatesConfig.value['texasInsuranceRebate'] = zcTexasInsuranceRebate
			// })
		},

		agentPointSetAllSubOk(data) {
			this.$emit('agentPointSetAllSubOk', data)
		},
		async upadteRebateRate(params) {
			try {
				await this.$api.rebateRateUdate(params)
			} catch (err) {
				throw err
			}
		}
	}
}
</script>

<style>
.pointAndRebate td .el-form-item__error {
	top: auto;
	bottom: 0px;
	left: 0;
}

.pointAndRebate td .el-form-item__content {
	min-height: 53px;
}

.pointAndRebate > .el-form-item > .el-form-item__content {
	overflow-y: auto;
}
</style>
